package br.com.escola.util;

import java.awt.image.RenderedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;

public class FileUtil
{
	public static String streamToString(InputStream is, String separador) throws IOException
	{
		return bufferToString(new BufferedReader(new InputStreamReader(is)), separador);
	}

	public static String fileToString(File f, String separador) throws IOException
	{
		return bufferToString(new BufferedReader(new FileReader(f)), separador);
	}

	public static String fileToString(FileReader fr) throws IOException
	{
		return bufferToString(new BufferedReader(fr), "");
	}

	public static String bufferToString(BufferedReader br, String separador) throws IOException
	{
		StringBuilder sb = new StringBuilder();
		String ln = null;

		while ((ln = br.readLine()) != null)
			sb.append(ln + separador);

		br.close();

		return sb.toString();
	}

	public static String pegaURL(String u) throws IOException
	{
		return pegaURL(u, "");
	}

	public static String pegaURL(String u, String separador) throws IOException
	{
		return FileUtil.fileToString(new File(u), separador);
	}

	public static void pegaImagemByURL(String u, File d) throws IOException
	{
		ImageWriter iw = ImageIO.getImageWritersByFormatName("jpeg").next();
		iw.setOutput(new FileImageOutputStream(d));

		ImageWriteParam iwParam = iw.getDefaultWriteParam();
		iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
		iwParam.setCompressionQuality(0.9f);

		RenderedImage ri = ImageIO.read(new URL(u));

		iw.write(null, new IIOImage(ri, null, null), iwParam);
	}

	public static void write(String f, String s) throws IOException
	{
		FileWriter fw = new FileWriter(f);

		fw.write(s);
		fw.close();
	}

	public static void main(String[] args)
	{
		try
		{
			System.out.println(fileToString(new File("E:/_/lingoo/_/interfilmes/filmes/b.html"), "\n"));
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
